import React, { Component } from 'react';
import { List, Button, Toast, ActivityIndicator, NoticeBar } from 'antd-mobile';
import PubSub from 'pubsub-js';
import { getDeviceNewVersion, upgradeDevice, checkUpgradeStatus, setDocumentTitle} from '../utils';
import { audio_operate } from '../components/AudioPlayOperate';
import IconUpgrade from '../images/upgrade.png';

/**
 * 升级界面
 */
const Item = List.Item
class Upgrade extends Component {

    constructor(props, context) {
        super(props, context);

        let isOnline = sessionStorage.getItem('online');
        if (isOnline) {
            isOnline = parseInt(isOnline, 10) === 1;
        } else {
            isOnline = false;
        }
        let uuid = '';
        let originalOsVersion = '';
        if (this.props.location && this.props.location.pathname) {
            let array = this.props.location.pathname.split(':');
            originalOsVersion = array[1].replace('/', '');
            uuid = array[2].replace('/', '');
        }
        this.state = {
            deviceName: localStorage.getItem('device_name'),
            appLogo: localStorage.getItem('app_logo'),
            isOnline: isOnline,
            uuid: uuid,
            packageId: 0,
            strategyId: '',
            newVersion: '',
            originalOsVersion: originalOsVersion,
            isUpgrading: false,
            isDisabled: true,
            waitCheck: true,
            failed: false,
        }
    }

    componentWillMount() {
        // 获取升级的信息
        getDeviceNewVersion(this.state.uuid, (result) => {
            if (result.errcode === 0) {
                const otaInfo = result.data;
                if (otaInfo) {
                    if (otaInfo.newOsVersion === otaInfo.originalOsVersion) {
                        this.setState({
                            newVersion: otaInfo.newOsVersion,
                        });
                        Toast.show('已经是最新版本', 1, false);
                    } else {
                        this.setState({
                            isDisabled: false,
                            packageId: otaInfo.packageId,
                            strategyId: otaInfo.strategyId,
                            newVersion: otaInfo.newOsVersion,
                            originalOsVersion: otaInfo.originalOsVersion
                        });
                    }
                } else {
                    Toast.show('已经是最新版本', 1, false);
                }
            } else {
                Toast.show('获取设备最新版本失败', 1, false);
            }
        })
    }

    componentDidMount() {
        setDocumentTitle('设备升级');
        PubSub.publish('contrlDevice', { type: audio_operate.upgrade_online, value: true });
        this.checkOnline = setInterval(() => {
            let isOnline = sessionStorage.getItem('online')
            if (isOnline) {
                isOnline = parseInt(isOnline, 10) === 1;
            }
            this.setState({
                isOnline: isOnline,
            });
        },1000)

        this.checkInterval = setInterval(() => {
            // 在线状态
            let isOnline = sessionStorage.getItem('online')
            if (isOnline) {
                isOnline = parseInt(isOnline, 10) === 1;
            }
            this.setState({
                waitCheck: false,
                isOnline: isOnline,
            });

            if (this.state.isUpgrading) {
                // 获取升级状态
                checkUpgradeStatus(this.state.uuid, (result) => {
                    console.log(result.data);
                    if (result.errcode === 0 && result.data) {
                        if (result.data.status === 'SUCCESS') {
                            this.setState({
                                isUpgrading: false,
                                isDisabled: true,
                                packageId: 0,
                                originalOsVersion: this.state.newVersion
                            });
                            localStorage.setItem('ota_version', this.state.newVersion);
                            Toast.success("设备升级成功", 2, false);
                        } else if (result.data.status === 'FAILED') {
                            this.setState({
                                failed: true,
                                isUpgrading: false,
                                isDisabled: true,
                            });
                        }
                    }
                })
            }
        }, 10000)

        // 如果两分钟之内还没有升级成功,需要中断检测升级状态
        this.checkTimeout = setInterval(() => {
            if (this.upgradeStartTime && this.state.isUpgrading) {
                const nowTime = parseInt(new Date().getTime() / 1000, 10);
                console.log(`nowTime:${nowTime}`);
                if (nowTime - this.upgradeStartTime >= 180) {
                    this.upgradeStartTime = null
                    this.setState({
                        failed: true,
                        isUpgrading: false,
                        isDisabled: false,
                    });
                    Toast.fail('设备升级超时,请点击重新升级设备', 2, false);
                }
            }
        }, 10000);

    }
    // 微信端 通知设备更新
    notifyUpgrade() {
        if (this.state.isOnline) {
            this.setState({ isUpgrading: true });
            upgradeDevice(this.state.uuid, this.state.packageId, this.state.strategyId, (result) => {
                if (result.errcode === 0) {
                    console.log(result.data.data);
                    if (parseInt(result.data.code, 10) === 0 && result.data.data) {
                        this.upgradeStartTime = parseInt(new Date().getTime() / 1000, 10)
                        PubSub.publish('contrlDevice', { type: audio_operate.force_offline, value: false });
                    } else {
                        this.setState({ isUpgrading: false });
                        Toast.show('升级失败', 1, false);
                    }
                } else {
                    this.setState({ isUpgrading: false });
                    Toast.show('升级失败,请检查网络连接', 1, false);
                }
            })
        } else {
            Toast.show('设备离线,请检查设备是否开启', 1, false);
        }
    }

    componentWillUnmount() {
        clearInterval(this.checkInterval);
        clearInterval(this.checkTimeout);
        clearInterval(this.checkOnline);
        Toast.hide();
    }

    /**
     * 按钮状态
     */
    getBtnText() {
        if (this.state.isUpgrading) {
            return '升级中...';
        }
        if (this.state.isOnline) {
            return this.state.packageId === 0 ? "已经是最新版本" : "发现新版本,点击升级";
        } else {
            return this.state.waitCheck ? "正在获取设备状态..." : "设备不在线,请先开启设备";
        }
    }

    render() {
        let disable = this.state.isUpgrading || (this.state.isDisabled || !this.state.isOnline);
        return (
            <div>
                {
                    this.state.failed &&
                    <NoticeBar mode="closable" icon={null}>
                        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' }}> 升级失败,请十分钟后再尝试重新升级</div>
                    </NoticeBar>
                }
                <div style={{
                    background: "#15a67c",
                    height: "160px",
                    width: "100%",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center"
                }}>
                    <img src={IconUpgrade} style={{ width: "64px", height: "64px" }} alt='' />
                </div>
                <Item
                    onClick={() => { }}>
                    <div style={styles.div_header}>
                        <div style={styles.div_header_img}>
                            <img src={this.state.appLogo} style={styles.head} alt='' />
                        </div>
                        <div style={{ marginLeft: 10, height: "56px"}}>
                            <p style={styles.name}>{this.state.deviceName}</p>
                            <p style={{
                                width: "80%", color: this.state.packageId === 0 ? "#707070" : "#ff0000",
                                fontSize: '13px',
                                paddingBottom: 0,
                                marginBottom: 3,
                                marginTop: 1,
                            }}>{this.state.packageId === 0 ? "当前版本" : "有新版本"}
                                <span style={{ color: "#707070" }}>
                                    {this.state.packageId === 0 ? this.state.originalOsVersion : this.state.newVersion}
                                </span>
                            </p>
                        </div>
                    </div>
                </Item>
                <div style={{ display: "flex", alignItems: "center", width: '100%', justifyContent: 'center', position: "fixed" }}>
                    <Button disabled={disable}
                        style={{ width: '80%', marginTop: 64, marginBottom: 26, height: 46 }}
                        onClick={this.notifyUpgrade.bind(this)}>
                        {this.getBtnText()}
                    </Button>
                </div>

                {
                    this.state.isUpgrading &&
                    <ActivityIndicator
                        toast
                        text="设备升级中..."
                        animating={this.state.isUpgrading} />
                }

            </div>
        );
    }
}

export default Upgrade;

const styles = {
    head: {
        width: '42px',
        height: '42px',
        borderRadius: '5px',
    },

    div_header: {
        width: '100%',
        height: "56px",
        display: 'flex'
    },
    div_header_img: {
        height: '56px',
        alignItems: "center",
        justifyContent: 'center',
        display: 'flex'
    },

    name: {
        width: document.documentElement.clientWidth / 5 * 3,
        height: '28px',
        marginRight: 16,
        color: "#15a67c",
        fontSize: '16px',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap',
        paddingBottom: 0,
        marginBottom: 3,
        marginTop: 1,
    },
};